package com.tenclass.common.interceptor;

import com.tenclass.common.model.CurrentUser;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.tenclass.common.constant.RequestConstant.*;

/**
 * feign拦截器
 * @author YIJIUE
 * @since 1.0.0
 */
public class FeignInterceptor implements RequestInterceptor {

    /**
     * 将解析出来的 user 信息传入模板中带给下游服务
     * @param template feign构造的http请求模板
     */
    @Override
    public void apply(RequestTemplate template) {
        // 传递用户信息到下游
        if (null != CurrentUser.get()) {
            template.header(CURRENT_USER, URLEncoder.encode(CurrentUser.get().toString(), StandardCharsets.UTF_8).replaceFirst("%3A", ":" ));
        }
        //添加token 适配老业务
        ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (request != null) {
            String accessToken = request.getRequest().getHeader(AUTHORIZATION);
            if (!StringUtils.isEmpty(accessToken)) {
                template.header(AUTHORIZATION, accessToken);
            }
        }
    }
}